sugarfreeControllers.controller('CoachController', ['$scope','$log','$filter', '$http', 'Utils','DictionarySerivce',function($scope,$log,$filter, $http, Utils,dicSerivce) {
	"use strict";
	
	$scope.retrieveContracts = function() {retrieveContracts();};
	
	$scope.selectContract = function ($event, contract_id) {selectContract($event, contract_id);};
	
	$scope.bindCoach = function () {bindCoach();};
	
	$scope.unbindCoach = function () {unbindCoach();};
	
	$scope.cancelbindCoach = function() {cancelbindCoach();};
	
	$scope.clearFields = function() {clearFields();};
	
	$scope.unDeleteForm = function(){unDeleteForm();};
	
	//Not used
	$scope.updateContract = function () {updateContract();};
    
  //Not used
  $scope.findByMobile = function () {findByMobile();};
    
  //Not used
  $scope.isCoachTypeSelected = function(id) {isCoachTypeSelected();};
    
  //Not used
  $scope.selectCoachType = function (id) {selectCoachType();};
    
  //Not used
  $scope.retrieveCoachTypes = function() {retrieveCoachTypes();};
    
	

	
	
	/////////////////////////
  //retrieve all contracted coach
  function retrieveContracts(){
	  Utils.setProcessParclose(true);
    var _queryContracts = "contract/query?" +
                          "uid=" + $scope.uid +
                          "&status=" + 3;
    var _urlContracts = $scope.apiUrl + _queryContracts;
    $http.get(_urlContracts).success(function(data) {
      $scope.contracts = data;
      Utils.setProcessParclose(false);
    });
	}
    
    // select contract in middle panel to show detail
    function selectContract($event, contract_id) {
      var found = $filter('filter') ($scope.contracts, {id: contract_id}, true);
      if (found.length ) {
        // unselect 
        if ( Utils.isUndefinedOrNull($scope.selectedContract) || $scope.selectedContract.id !== found[0].id) {
          $scope.selectedContract = found[0];
          Utils.setParclose(true);
          $log.info("$scope.contracts",$scope.contracts);
          $log.info("selectContract...",$scope.selectedContract);
        }
        else {
          $scope.selectedContract = null;
        }
      } else {
        // not found
        $scope.selectedContract = null;
      }
      $event.stopPropagation();
    }

    function retrieveCoachTypes() {
      var _queryCoachType = "filter/coachTypes?" +
                            "uid=" + $scope.uid;
      var _urlCoachType = $scope.apiUrl + _queryCoachType;

      $http.get(_urlCoachType).success(function(data) {
        $scope.coachTypes = data;
        console.log($scope.coachTypes);
      });
    }
    

    function selectCoachType(id) {
      var idx = $scope.selectedCoachType.indexOf(id);
      // is currently selected
      if ( idx > -1 ) {
        $scope.selectedCoachType.splice(idx, 1);
      } else {
        $scope.selectedCoachType.push(id);
      }
      console.log('selectedCoachType:', id, $scope.selectedCoachType);
    }
    
    
    function isCoachTypeSelected(id) {
      var idx = $scope.selectedCoachType.indexOf(id);
      if (idx > -1 ) {
        return true;
      } else {
        return false;
      }
      
    }
    
    
    

    // search coach by mobile so that staff can verify their name
    function findByMobile() {
      var _queryCoachByMobile = "coach/findByMobile";
      var _dataStr = "?mobile="+ $scope.mobile;
      var _urlCoachByMobile = $scope.apiUrl + _queryCoachByMobile + _dataStr;
      $http.get(_urlCoachByMobile).success(function(data) {
        if (data.id !== 0 ) {
          $scope.coachbymobile = data;
        }
        console.log ('findByMobile:', data, $scope.coachbymobile);
      });
      $scope.mobile = "";

    }

  // bind coach to gym
  function bindCoach() {
	  Utils.setProcessParclose(true);
	  console.log("$scope.selectedContract",$scope.selectedContract);
      if (!Utils.isUndefinedOrNull($scope.selectedContract) ) { 
        var _queryBindCoach = "contract/bind";
        var _dataStr = "id=" + $scope.selectedContract.id;
        var _urlBindCoach = $scope.apiUrl + _queryBindCoach;
        console.log("bind coach url: ", _urlBindCoach, _dataStr);
        $http ({
            method: 'POST',
            url: _queryBindCoach,
            data: _dataStr,
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
          }).
            then(function(response) {
              alert("教练绑定成功");
              clearFields();
              Utils.setProcessParclose(false);
              Utils.setParclose(false);
              console.log('bind coach success', response);
              retrieveContracts();
            }, function(response){
              alert("教练绑定失败");
              Utils.setParclose(false);
              clearFields();
              console.log('bind coach failed', response.data);
            });
      }
    }
    
   function cancelbindCoach() {
      console.log("cancelBindCoach", $scope.coachbymobile.id);
      $scope.coachbymobile = null;
      $scope.selectedCoachType = [];
   }

    // unbind coach with studio
    // TOTEST: pending test
   function unbindCoach() {
      if (!Utils.isUndefinedOrNull($scope.selectedContract) ) {
        var _queryUnBindCoach = "contract/unbind";
        var _dataStr = "uid=" + $scope.uid +
                       "&id=" + $scope.selectedContract.id;
        var _urlUnBindCoach = $scope.apiUrl + _queryUnBindCoach;
        console.log("unbindCoach url:", _queryUnBindCoach, _dataStr);
        Utils.setProcessParclose(true);  
        $http ({
            method: 'POST',
            url: _urlUnBindCoach,
            data: _dataStr,
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
          }).
            then(function(response) {
              alert("教练删除成功");
              clearFields();
              $scope.page.useDelConfirm = false;
              Utils.setProcessParclose(false);
              Utils.setParclose(false);
              console.log('unbind success', response);
              retrieveContracts();
            }, function(response){
              alert("教练删除失败");
              clearFields();
              Utils.setParclose(false);
              console.log('unbind coach failed', response.data);
            });
      }
    }
    

    function updateContract() {
      var coachTypesSelected = 0;
      angular.forEach($scope.selectedCoachType, function(item){
        coachTypesSelected += item;
      });
      if (coachTypesSelected === 0) {
        $scope.errormsg = "请选择授课类型";
        return;
      }

      var _queryUpdateContract = "contract/edit";
      var _data = {
          type: coachTypesSelected,
          id: $scope.selectedContract.id, 
          uid: 1
      };
      var _dataStr = "uid=" + $scope.uid +
                    "&type=" + coachTypesSelected +
                    "&id=" + $scope.selectedContract.id;

      var _urlUpdateContract = $scope.apiUrl + _queryUpdateContract;
      var _urlUpdateContract2 = $scope.apiUrl + _queryUpdateContract + "?" + _dataStr;

      $http ({
            method: 'POST',
            url: _urlUpdateContract,
            data: _dataStr,
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
          }).
            then(function(response) {
              alert("教练信息修改成功");    
              console.log('unbind coach success', response);
              $scope.retrieveLessonTpls();
              $scope.clearFields();
            }, function(response){
              alert("教练信息修改失败");  
              console.log('unbind coach failed', response.data);
            });
    }

    function clearFields(){
      $scope.selectedContract = null;
      //$scope.selectedCoachType = [];
    }
    
    
    function unDeleteForm(){
    	$scope.page.useDelConfirm = false;
    }

    function initData() {
        retrieveContracts();
        
        $scope.page = {
        		useDelConfirm:false
        };
    }

    initData();
}]);